;
(function () {
  Array.prototype.removeRepeatBuildingAndFLoor = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  new Vue({
    el: '#merger_payment',
    data: {
      ids: hlUrlUtil.GetQueryString('ids'),
      projectId: hlUrlUtil.GetQueryString('projectId'),
      type: hlUrlUtil.GetQueryString('type'),
      // 解码
      customName: decodeURI(hlUrlUtil.GetQueryString('name')),
      payfn: [{
          name: '现金支付',
          code: 'XJ'
        },
        {
          name: '银行转账',
          code: 'BK'
        },
        {
          name: '支票',
          code: 'ZP'
        },
				{
				  name: '银行汇票',
				  code: 'BD'
				},
				{
				  name: '银行本票',
				  code: 'BN'
				},
				{
				  name: '信用卡',
				  code: 'CC'
				},
        {
          name: '支付宝',
          code: 'AP'
        },
        {
          name: '微信',
          code: 'WX'
        },
        {
          name: '其他',
          code: 'ET'
        }
      ],
      selectedPay: [],
      amountWpay: '',
      amountCopyWpay: '',
      lateFeeTPay: '',
      lateFeeCopyTPay: '',
      paymentTime: '',
      paymentNo: '',
      memo: '',
      fileList: [],

      costList: [],
			receiptAccountList: [],
			accountCode: []
    },
    filters: {
      timestamp: function (time) {
        if (!time) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      billState: function (state) {
        if (!state) return '';
        return hlCodeConvert.billPaymentState(state)
      },
      toFixed2: function (n) {
        return Number(n).toFixed(2)
      },
      billPayWay: function (state) {
        return hlCodeConvert.billPayWay(state)
      },
      payfn: function (str) {
        var result = '';
        switch (str) {
          case 'XJ':
            result = '现金支付'
            break;
          case 'BK':
            result = '银行转账'
            break;
					case 'BD':
					  result = '银行汇票'
					  break;
					case 'BN':
					  result = '银行本票'
					  break;
					case 'CC':
					  result = '信用卡'
					  break;
          case 'ZP':
            result = '支票'
            break;
          case 'AP':
            result = '支付宝'
            break;
          case 'WX':
            result = '微信'
            break;
          case 'ET':
            result = '其他'
            break;
        }
        return result
      },
      //千分位
      formatNum: function (n) {
        return hlNumberUtil.formatNum(n)
      },
      absNum: function (n) {
        return Math.abs(n)
      }
    },
    computed: {
      cumulation() {
        let num = 0
        if(this.type == 'T'){
          this.costList.map(item => {
            item.billExpenseList.map(single => {
              num = num + Number(single.totalAmount)
            })
          })
        }else{
          this.costList.map(item => {
            item.billExpenseList.map(single => {
              num = num + Number(single.onceAmountPay) + Number(single.onceLateFeePay)
            })
          })
        }
        return num
      },
      //应收本金总和
      ys_yt(){
        let num = 0
        this.costList.map(item => {
          item.billExpenseList.map(single => {
            num = num + Number(single.ys_yt)
          })
        })
        return num
      },
      // 滞纳金总和
      znj_total(){
        let num = 0
        this.costList.map(item => {
          item.billExpenseList.map(single => {
            num = num + Number(single.znjAmount)
          })
        })
      
        return num
      },
      total() {
        if(this.type == 'S'){
          this.amountWpay = Number(this.ys_yt).toFixed(2)
          this.amountCopyWpay = Number(this.ys_yt).toFixed(2)
        }else{
          this.amountWpay =   Number(this.ys_yt + this.znj_total).toFixed(2)
          this.amountCopyWpay = Number(this.ys_yt + this.znj_total).toFixed(2)
        }
        this.lateFeeTPay = (this.znj_total).toFixed(2)
        this.lateFeeCopyTPay = this.znj_total
        if(this.ys_yt + this.znj_total < 0){
          this.costList.map(item => {
            item.billExpenseList.map((single, one) => {
              single.onceAmountPay = single.totalAmount
            })
          })
        }
        return this.ys_yt + this.znj_total
      },
    },
    methods: {
      // 账单批量收款-费项列表查询
      getBillDetail() {
        hlhttp.get({
          url: 'bill_batch_detail/bill,expenses',
          data: {
            bill_ids: this.ids,
          },
          success: res => {
            res.map(item => {
              item.billExpenseList.map(single => {
                single.memo = single.memo || ''
                single.bjAmount = Number((single.amountReceived - single.amountPayed - single.amountDerate - single.carryOverTotalAmount).toFixed(2)) //应收本金
                single.znjAmount = Number((single.lateFeeReceived - single.lateFeePayed - single.lateFeeDerate).toFixed(2)) //应收滞纳金
                if(single.amountRefund){
                  single.ys_yt = - single.refundTPay  //应收本金总和
                  single.totalAmount  = Number(- single.refundTPay  + single.znjAmount).toFixed(2)
                }else{
                  single.ys_yt = single.bjAmount  //应收本金总和
                  single.totalAmount  = Number(single.bjAmount  + single.znjAmount).toFixed(2)   //single.refundTPay(应退本金)   totalAmount(金额)
                }
                single.onceAmountPay = Number(single.ys_yt).toFixed(2)
                single.onceLateFeePay = Number(single.znjAmount).toFixed(2)
              })  
            })
            
						
						let receiptAccountList = []
						res.map(item => {
							if (item.receiptAccountList) {
								receiptAccountList = receiptAccountList.concat(item.receiptAccountList)
							}
						})
						receiptAccountList = hlArrayUtil.removeRepeat(receiptAccountList, 'accountCode')
						console.log(receiptAccountList)
						receiptAccountList.map(item => {
							item.code = item.accountCode
							item.name = item.accountName+' ('+item.bankAccount+')'
						})
						// hlArrayUtil.removeRepeat
						this.accountCode = receiptAccountList.length ? [receiptAccountList[0]['code']] : []
						this.receiptAccountList = receiptAccountList
            this.costList = res
          }
        })
      },
      // 输入本次实收本金
      setAmountWpay() {
        if(this.ys_yt < this.amountWpay){
          hl.toast('本次实收本金不能大于应收本金')
          this.amountWpay = ''
          return
        }
        if(this.amountWpay < 0){
          hl.toast('本次实收本金不能小于0')
          this.amountWpay = ''
          return
        }
        num = Number(this.amountCopyWpay) -  Number(this.amountWpay)

        this.costList.map(item => {
          item.billExpenseList.map((single, one) => {
            if(single.ys_yt >= 0 && single.totalAmount >= 0){
              if(num < 0){
                let amount = single.ys_yt - single.onceAmountPay
                if(amount > num*-1){
                  single.onceAmountPay = Number(single.onceAmountPay + num*-1).toFixed(2)
                  num = 0
                }else{
                  single.onceAmountPay = single.ys_yt
                  num = num + amount
                }
              }
              if(num > 0){
                if(single.onceAmountPay > num){
                  single.onceAmountPay = Number(single.onceAmountPay - num).toFixed(2)
                  num = 0
                }else{
                  num = num - single.onceAmountPay
                  single.onceAmountPay = 0
                }
              }
              
            }
          })
        })
        this.amountCopyWpay = JSON.parse(JSON.stringify(this.amountWpay))
        this.calculateJS()
      },
      // 输入本次实收滞纳金
      setLateFeeTPay() {
        if(this.znj_total < this.lateFeeTPay){
          hl.toast('本次实收滞纳金不能大于应收滞纳金')
          this.lateFeeTPay = ''
          return
        }
        if(this.lateFeeTPay < 0){
          hl.toast('本次实收滞纳金不能小于0')
          this.lateFeeTPay = ''
          return
        }
        num = Number(this.lateFeeCopyTPay) -  Number(this.lateFeeTPay)
        this.costList.map(item => {
          item.billExpenseList.map((single, one) => {
            if(single.znjAmount >= 0 && single.totalAmount >= 0){
              if(num < 0){
                let amount = single.znjAmount - single.onceLateFeePay
                if(amount > num*-1){
                  single.onceLateFeePay = Number(single.onceLateFeePay + num*-1).toFixed(2)
                  num = 0
                }else{
                  single.onceLateFeePay = single.znjAmount
                  num = num + amount
                }
              }
              if(num > 0){
                if(single.onceLateFeePay > num){
                  single.onceLateFeePay = Number(single.onceLateFeePay - num).toFixed(2)
                  num = 0
                }else{
                  num = num - single.onceLateFeePay
                  single.onceLateFeePay = 0
                }
              }
              
            }
          })
        })
        console.log(this.costList)
        this.lateFeeCopyTPay = JSON.parse(JSON.stringify(this.lateFeeTPay))
        this.calculateJS()
      },
      // 校验本次实收// 校验滞纳金
      checkAmount(index, one,type) {
        if(type == 's'){
          if(this.costList[index].billExpenseList[one].ys_yt < 0){
            if (this.costList[index].billExpenseList[one].onceAmountPay < this.costList[index].billExpenseList[one].ys_yt) {
              hl.toast('实收本金不可小于应收本金')
              this.costList[index].billExpenseList[one].onceAmountPay = ''
              return
            }
            if (this.costList[index].billExpenseList[one].onceAmountPay > 0) {
              hl.toast('实收本金不可为正数')
              this.costList[index].billExpenseList[one].onceAmountPay = ''
              return
            }
          }else{
            if (this.costList[index].billExpenseList[one].onceAmountPay > this.costList[index].billExpenseList[one].ys_yt) {
              hl.toast('实收本金不可大于应收本金')
              this.costList[index].billExpenseList[one].onceAmountPay = ''
              return
            }
            if (this.costList[index].billExpenseList[one].onceAmountPay < 0) {
              hl.toast('实收本金不可为负数')
              this.costList[index].billExpenseList[one].onceAmountPay = ''
              return
            }
          }
          this.calculateJS()
        }else{
          if (this.costList[index].billExpenseList[one].onceLateFeePay > this.costList[index].billExpenseList[one].znjAmount) {
            hl.toast('实收滞纳金不可大于应收滞纳金')
            this.costList[index].billExpenseList[one].onceLateFeePay = ''
            return
          }
          if (this.costList[index].billExpenseList[one].onceLateFeePay < 0) {
            hl.toast('实收滞纳金不可为负数')
            this.costList[index].billExpenseList[one].onceLateFeePay = ''
            return
          }
          this.calculateJS()
        }
      },

      // 编辑费用明细后重新统计费用结算
      calculateJS(){
        this.amountWpay = 0.00
        this.lateFeeTPay = 0.00
        this.costList.map(item =>{
          item.billExpenseList.map(single =>{
            this.amountWpay = this.amountWpay + Number(single.onceAmountPay)
            this.lateFeeTPay = this.lateFeeTPay + Number(single.onceLateFeePay)
          })
        })
        this.amountWpay = Number(this.amountWpay).toFixed(2)
        this.lateFeeTPay = Number(this.lateFeeTPay).toFixed(2)
        if(!this.amountWpay){
          this.amountWpay = '0.00'
        }
        if(!this.lateFeeTPay){
          this.lateFeeTPay = '0.00'
        }
      },  

      // 确认收款前的校验
      checkSubmit(){
        if(!this.amountWpay){
          hl.toast('请输入本次实收本金')
          return false
        }
        if(!this.lateFeeTPay && this.total >= 0){
          hl.toast('请输入本次实收滞纳金')
          return false
        }
        if(!this.selectedPay.length){
          hl.toast('请选择收款方式')
          return false
        }
        if(!this.paymentTime){
          hl.toast('请输入收款时间')
          return false
        }
        let flag = true

        this.costList.map(item =>{
          item.billExpenseList.map(single =>{
            if(!single.onceAmountPay){
              flag = false
            }
          })
        })
        if(!flag){
          hl.toast('请填写本次实收')
        }
        if(this.total < this.cumulation){
          hl.toast('本次实收不可大于本次应收')
          return false
        }
        if(this.type == 'S' && this.cumulation < 0){
          hl.toast('本次实收不可小于0')
          return false
        }
        return flag
      },
      //确认收款
      submitBill() {
        if(!this.checkSubmit()) return
        let vouchers = this.fileList + ''
        let data = JSON.parse(JSON.stringify(this.costList)) 
        data.map(item =>{
          item.bill_id = item.billId,
          item.project_id = this.projectId,
          item.payment_way = this.selectedPay + '',
          item.payment_time = this.paymentTime,
          item.payment_no = this.paymentNo || '#',
          item.memo = this.memo || '#',
          item.vouchers = vouchers || '#'
          item.amount_wpay = 0
          item.lateFeeTPay = 0
					item.receiptAccount = this.accountCode.toString() || '#'
          item.billExpenseList.map(single =>{
            single.memo = single.memo || '#'
            single.onceLateFeePay  = single.onceLateFeePay || '0'
            item.amount_wpay = Number(item.amount_wpay) + Number(single.onceAmountPay)
            item.lateFeeTPay = Number(item.lateFeeTPay) + Number(single.onceLateFeePay)
          })
 
        })
        hlhttp.post({
          url: 'bill/balance_batch',
          data: {
            bill_infos: JSON.stringify(data)
          },
          success: res => {
            hl.toast('收款成功')
            hlUrlUtil.goTo('financeList')
          }
        })

      },
      //上传支付凭证
      uploadImg() {
        $('.js-trigger-upload').trigger('click')
      },
      //删除图片
      delPic: function (i) {
        this.fileList.splice(i, 1)
      },
    },
    mounted: function () {
      this.getBillDetail()
      var _this = this;
      uploader('.bill-settlement','.js-trigger-upload', uploadUrl, function (src) {
        _this.fileList.push(JSON.parse(src.response).url)
      })
    }
  })
}())